package Thread.Test.Test4;

import java.util.Random;

public class MyThread extends Thread{

    //红包现存总数
    public static int money = 100;

    //红包个数
    public static int number;

    //设置锁对象
    public static Object obj =new Object();
    public MyThread()
    {

    }
    public MyThread(int i)
    {
        number = i;
    }

    @Override
    public void run() {
        synchronized (obj) {

            if (money != 0) {
                //money!=0,说明还有红包

                //判断是否时最后一次
                if (number == 1) {
                    System.out.println(getName() + "抢到了" + money + "元");
                    money = 0;
                } else {
                    //不是最后一次,运用随机数
                    Random r = new Random();
                    int money_u = r.nextInt(money);
                    money = money - money_u;
                    number--;
                    System.out.println(getName() + "抢到了" + money_u + "元");
                }

            } else {
                //没有红包了
                System.out.println(getName() + "没有抢到红包");
            }
        }
    }
}
